<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="山峰名称" :label-width="labelWidth" prop="name">
        <ElInput v-model="form.name" />
      </ElFormItem>
      <ElFormItem label="经度" :label-width="labelWidth" prop="longitude">
        <ElInput v-model="form.longitude" />
      </ElFormItem>
      <ElFormItem label="纬度" :label-width="labelWidth" prop="latitude">
        <ElInput v-model="form.latitude" />
      </ElFormItem>
      <ElFormItem label="山峰位置" :label-width="labelWidth" prop="position">
        <ElInput v-model="form.position" />
      </ElFormItem>
      <ElFormItem label="山峰高度" :label-width="labelWidth" prop="height">
        <div class="mo-input--number">
          <ElInputNumber v-model="form.height" controls-position="right" clearable />
          <div class="define-append">米</div>
        </div>
      </ElFormItem>
      <ElFormItem label="山峰简介" :label-width="labelWidth" prop="content">
        <ElInput type="textarea" v-model="form.content" />
      </ElFormItem>
      <ElFormItem label="山峰图片" :label-width="labelWidth">
        <UploadImgs :file-size="8" :limit="8" :disabled="isView" v-model:fileList="fileList">
          <template #empty>
            <el-icon><Picture></Picture></el-icon>
            <span>请上传照片</span>
          </template>
          <template #tip>支持可拖拽上传</template>
        </UploadImgs>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { MountainPeak } from '@api/tby/summarize/MountainPeak/interface'
import { FormType } from '@/enums'
import { getMountainPeakDetail, saveOrUpdateMountainPeak } from '@api/tby/summarize/MountainPeak'
import {
  TbyFileBusiness,
  listFileBusiness,
  validateLongitude,
  validateLatitude,
  checkDecimalMaxNum
} from '@api/tby/common/common'
import UploadImgs from '@/components/Upload/Imgs.vue'
import type { UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
const fileList = ref<UploadUserFile[]>([])
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<MountainPeak.Form>>({})

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const validateHeight = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  if (!checkDecimalMaxNum(value + '', 2)) {
    callback(new Error('最多支持两位小数'))
  }
  const regExp = /^\d+(\.\d+)?$/
  if (!regExp.test(value)) {
    callback(new Error('请输入有效的数字！'))
    return
  }
  let height = parseFloat(value)
  if (height > 10000 || height <= 0) {
    callback(new Error('山峰高度范围在 1 - 10000 之间'))
    return
  }
  callback()
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入山峰名称', trigger: 'blur' },
    { max: 20, message: '山峰名称最大20个字符', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { max: 32, message: '经度最大32个字符', trigger: 'blur' },
    { validator: validateLongitude, trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { max: 32, message: '纬度最大32个字符', trigger: 'blur' },
    { validator: validateLatitude, trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入山峰位置', trigger: 'blur' },
    { max: 20, message: '山峰位置最大20个字符', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入山峰高度', trigger: 'blur' },
    { validator: validateHeight, trigger: 'blur' }
  ]
})

const open = async (type: FormType, id?: number) => {
  fileList.value = []
  form.value = {}
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getMountainPeakDetail(id!)
      loading.value = false
      form.value = data
      const response = await listFileBusiness('MOUNTAIN_PEAK', id!)
      if (response.code === 0) {
        response.data.forEach((element: TbyFileBusiness.Form) => {
          fileList.value.push({
            url: element.fileUrl,
            name: element.fileName
          })
        })
      }
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) return
  let array = fileList.value.map(item => item.url)
  if (!array || array.length == 0) {
    ElMessage({
      type: 'error',
      message: '请上传山峰照片!'
    })
    return
  }
  form.value.attach = array.join(',')
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateMountainPeak(formData).then(response => {
      console.log(response)
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>

<style scoped lang="scss">
.mo-input--number {
  border: 1px solid #dcdfe6;
  display: flex;
  border-radius: 4px;
  .el-input-number--mini {
    flex: 1;
  }
  ::v-deep .el-input__inner {
    border: none !important;
  }
}
.define-append {
  width: 40px;
  display: inline-block;
  background: #f5f7fa;
  padding: 0px 3px;
  border-left: none;
  height: 32px;
  line-height: 32px;
  color: #909399;
  font-size: 12px;
  text-align: center;
}
</style>
